#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from datetime import datetime

from contextlib import contextmanager

from flask_sqlalchemy import SQLAlchemy as _sqlalchemy, BaseQuery
from sqlalchemy import Integer, Column, SmallInteger

from app.libs.error_code import NotFound


class SQLAlchemy(_sqlalchemy):
    @contextmanager
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e


class Query(BaseQuery):
    def filter_by(self, **kwargs):
        if 'is_delete' not in kwargs.keys():
            kwargs['is_delete'] = 1
        return super().filter_by(**kwargs)

    def get_or_404(self, ident):
        rv = self.get(ident)
        if not rv:
            raise NotFound()
        return rv

    def first_or_404(self):
        rv = self.first()
        if not rv:
            raise NotFound()
        return rv



db = SQLAlchemy(query_class=Query)


class Base(db.Model):
    __abstract__ = True
    create_time = Column(Integer)
    is_delete = Column(SmallInteger, default=1)

    def __init__(self):
        self.create_time = int(datetime.now().timestamp())

    @property
    def create_datetime(self):
        if self.create_time:
            return datetime.fromtimestamp(self.create_time)
        else:
            return None

    def set_attrs(self, attrs_dict):
        for key, value in attrs_dict.items():
            if hasattr(self, key) and key != id:
                setattr(self, key, value)

    def delete(self):
        self.is_delete = 0

    def __getitem__(self, item):
        return getattr(self, item)